package com.android.wnba.activity;

import java.net.URI;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.xmlpull.v1.XmlSerializer;
import org.xmlrpc.android.XMLRPCClient;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.wnba.R;
import com.android.wnba.model.LoginItem;
import com.android.wnba.util.Constants;
import com.android.wnba.util.DialogUtil;
import com.android.wnba.util.DialogUtil.WarningDialogListener;
import com.android.wnba.util.Util;
import com.android.wnba.util.http.HttpUtil;

public class LoginActivity extends Activity implements WarningDialogListener {
	private static final int DIALOG_SUBMITING = 0;
	private static final int DIALOG_LOGIN_ERROR = 1;
	private static final int DIALOG_LOGIN_TIMEOUT = 2;

	Context ctx;

	Button loginBtn;
	EditText nameEt, pwdEt;
	String name, pwd;
	String encodePwd, verifyCode;
	String token;
	// WnbaResponse response;
	LoginItem loginItem;

	boolean halfWayFlag = false;

	XMLRPCClient client;
	URI uri;
	Map<String, String> map;
	XmlSerializer serializer;
	String resContent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		ctx = this;

		initData();
		initViews();
	}

	void initData() {
		uri = URI.create(Constants.URL_SERVER);
		client = new XMLRPCClient(uri);
	}

	private void initViews() {
		nameEt = (EditText) findViewById(R.id.login_et_name);
		pwdEt = (EditText) findViewById(R.id.login_et_pwd);

		loginBtn = (Button) findViewById(R.id.login_btn_login);
		loginBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				login();
			}
		});
	}

	private void login() {
		if (!Util.isNetWorking(ctx)) {
			Toast.makeText(ctx, R.string.pub_bad_net, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		name = nameEt.getText().toString().trim();
		pwd = pwdEt.getText().toString().trim();
		Util.debug("name+pwd:" + name + "<-->" + pwd);
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
			Toast.makeText(ctx, R.string.login_noti_intput_namepwd,
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (!Constants.USER_PWD_PATTERN.matcher(pwd).matches()) {
			// 密码中有非法字符
			Toast.makeText(ctx, R.string.login_noti_wrang_pwd,
					Toast.LENGTH_SHORT).show();
			return;
		}
		byte[] key = DigestUtils.md5(Util.getUTF8Bytes(pwd));
		encodePwd = new String(Util.encode(key));
		if (TextUtils.isEmpty(encodePwd)) {
			return;
		}
		// 登陆操作
		LoginTask loginTask = new LoginTask();
		loginTask.execute();
	}

	private class LoginTask extends AsyncTask<Void, Integer, Boolean> {

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_SUBMITING);
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// Object[] params2 = new Object[] { name, encodePwd };
			//
			// try {
			// Object res = client.callEx("dolphin.login2", params2);
			// map = (Map<String, String>)(res);
			// resContent = res.toString();
			// } catch (XMLRPCException e) {
			// e.printStackTrace();
			// return false;
			// }
			// return true;

			loginItem = HttpUtil.checkLogin(ctx, name, encodePwd);
			if (loginItem == null) {
				return false;
			} else {
				return true;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO
			removeDialog(DIALOG_SUBMITING);
			// Util.shortToast(ctx, response.object.toString());
			if (result) {
				if (loginItem.member_id == 0) {
					// 用户名密码错误
					showDialog(DIALOG_LOGIN_ERROR);
				} else {
					hideInput();
					// 登陆成功
					Util.shortToast(ctx, "member_id:" + loginItem.member_id);
					startActivity(new Intent(LoginActivity.this,
							TabMainActivity.class));
				}
			} else {
				// 登陆失败
				showDialog(DIALOG_LOGIN_TIMEOUT);
			}
		}
	}

	private void hideInput() {
		InputMethodManager ims = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		ims.hideSoftInputFromWindow(nameEt.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
		ims.hideSoftInputFromWindow(pwdEt.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SUBMITING:
			return DialogUtil.createIndeterminateProgressDialog(this, id,
					getString(R.string.login_noti_submmting), false, null);
		case DIALOG_LOGIN_ERROR:
			return DialogUtil.createOKWarningDialog(ctx, id, null,
					getString(R.string.login_noti_error), null);
		case DIALOG_LOGIN_TIMEOUT:
			return DialogUtil.createRetryWarningDialog(this, id, null,
					R.string.pub_timeout, this);
		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Util.debug("resultCode:" + requestCode);
		if (resultCode == Constants.REQUEST_HARF_WAY_LOGIN) {
			halfWayFlag = true;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case (KeyEvent.KEYCODE_BACK): {
			// Util.exitApp(ctx);
			finish();
			return true;
		}
		}
		return super.onKeyDown(keyCode, event);
	}

	public void onWarningDialogCancel(int id) {
		// TODO Auto-generated method stub

	}

	public void onWarningDialogOK(int id) {
		// TODO Auto-generated method stub
		login();
	}
}